package com.ztr.test.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;  
import java.net.SocketException;  
import java.util.Enumeration;  
  
public class FirstIPv4AddressOfInterface {  
    public static void main(String[] args) {  
        String interfaceName = "wlan2"; // 设置要查找的接口名称  
        InetAddress ipv4Address = null;  
        try {  
            NetworkInterface into = NetworkInterface.getByName(interfaceName);
            if (into != null) {
                Enumeration<InetAddress> adders = into.getInetAddresses();
                while (adders.hasMoreElements()) {
                    InetAddress addr = adders.nextElement();
                    if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && addr instanceof java.net.Inet4Address) {
                        ipv4Address = addr;
                        break; // 找到第一个符合条件的IPv4地址后跳出循环
                    }
                }
                if (ipv4Address != null) {
                    System.out.println("接口名称: " + into.getName() + " IP地址: " + ipv4Address.getHostAddress());
                } else {
                    System.out.println("接口 " + interfaceName + " 没有找到符合条件的IPv4地址。");
                }
            } else {
                System.out.println("找不到名为 " + interfaceName + " 的网络接口。");
            }
        } catch (SocketException e) {
            e.printStackTrace();  
        }  
    }  
}